<template>
  <div class="max-w-7xl mx-auto p-6">
    <div class="bg-white rounded-lg shadow-lg">
      <!-- 页面标题 -->
      <div class="border-b border-gray-200 px-6 py-4">
        <div class="flex justify-between items-center">
          <div>
            <h1 class="text-2xl font-bold text-gray-800">模型配置管理</h1>
            <p class="text-gray-600 mt-2">管理AI模型配置，支持添加、编辑和删除</p>
          </div>
          <button
            @click="showAddModal = true"
            class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            <span>添加配置</span>
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="modelConfigStore.isLoading" class="p-6 text-center">
        <div class="inline-flex items-center space-x-2">
          <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
          <span class="text-gray-600">加载配置中...</span>
        </div>
      </div>

      <!-- 配置列表 -->
      <div v-else class="p-6">
        <div v-if="!modelConfigStore.configs || modelConfigStore.configs.length === 0" class="text-center py-12">
          <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
          </svg>
          <h3 class="mt-2 text-sm font-medium text-gray-900">暂无配置</h3>
          <p class="mt-1 text-sm text-gray-500">开始添加您的第一个AI模型配置</p>
          <div class="mt-6">
            <button
              @click="showAddModal = true"
              class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
            >
              <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
              添加配置
            </button>
          </div>
        </div>

        <div v-else class="grid gap-4">
          <div
            v-for="config in (modelConfigStore.configs || [])"
            :key="config.id"
            class="border border-gray-200 rounded-lg p-6 hover:shadow-md transition-shadow"
          >
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-4">
                <div class="flex-shrink-0">
                  <div :class="getProviderIconClass(config.provider)" class="w-12 h-12 rounded-lg flex items-center justify-center">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                  </div>
                </div>
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <h3 class="text-lg font-semibold text-gray-900">{{ config.name }}</h3>
                    <span v-if="config.isDefault" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      默认
                    </span>
                    <span :class="config.isActive ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                      {{ config.isActive ? '启用' : '禁用' }}
                    </span>
                  </div>
                  <p class="text-sm text-gray-600 mt-1">{{ config.provider }} - {{ config.model }}</p>
                  <div class="flex items-center space-x-4 mt-2 text-sm text-gray-500">
                    <span>Temperature: {{ config.parameters?.temperature || config.temperature || 'N/A' }}</span>
                    <span>Max Tokens: {{ config.parameters?.maxTokens || config.maxTokens || 'N/A' }}</span>
                    <span v-if="config.updatedAt">更新时间: {{ formatDate(config.updatedAt) }}</span>
                  </div>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <button
                  @click="testConfig(config)"
                  :disabled="testingConfigId === config.id"
                  class="text-blue-600 hover:text-blue-800 p-2 rounded-lg hover:bg-blue-50 transition-colors disabled:opacity-50"
                  title="测试连接"
                >
                  <svg v-if="testingConfigId === config.id" class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                  </svg>
                  <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                  </svg>
                </button>
                <button
                  @click="editConfig(config)"
                  class="text-gray-600 hover:text-gray-800 p-2 rounded-lg hover:bg-gray-50 transition-colors"
                  title="编辑"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                  </svg>
                </button>
                <button
                  @click="deleteConfig(config)"
                  class="text-red-600 hover:text-red-800 p-2 rounded-lg hover:bg-red-50 transition-colors"
                  title="删除"
                >
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑配置模态框 -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900">
              {{ showEditModal ? '编辑配置' : '添加配置' }}
            </h3>
            <button @click="closeModal" class="text-gray-400 hover:text-gray-600">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <form @submit.prevent="saveConfig" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">配置名称</label>
                <input
                  v-model="formData.name"
                  type="text"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="例如：OpenAI GPT-4"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">提供商</label>
                <select
                  v-model="formData.provider"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择提供商</option>
                  <option value="siliconflow">硅基流动</option>
                  <option value="openai">OpenAI</option>
                  <option value="claude">Anthropic Claude</option>
                  <option value="qwen">阿里云通义千问</option>
                  <option value="deepseek">DeepSeek</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">模型</label>
                <select
                  v-model="formData.model"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择模型</option>
                  <!-- OpenAI 模型 -->
                  <optgroup label="OpenAI">
                    <option value="gpt-4o">GPT-4o</option>
                    <option value="gpt-4o-mini">GPT-4o Mini</option>
                    <option value="gpt-4-turbo">GPT-4 Turbo</option>
                    <option value="gpt-4">GPT-4</option>
                    <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
                  </optgroup>
                  <!-- DeepSeek 模型 -->
                  <optgroup label="DeepSeek">
                    <option value="deepseek-chat">DeepSeek Chat</option>
                    <option value="deepseek-reasoner">DeepSeek Reasoner</option>
                    <option value="deepseek-coder">DeepSeek Coder</option>
                  </optgroup>
                  <!-- Anthropic Claude 模型 -->
                  <optgroup label="Anthropic Claude">
                    <option value="claude-3-5-sonnet-20241022">Claude 3.5 Sonnet</option>
                    <option value="claude-3-5-haiku-20241022">Claude 3.5 Haiku</option>
                    <option value="claude-3-opus-20240229">Claude 3 Opus</option>
                    <option value="claude-3-sonnet-20240229">Claude 3 Sonnet</option>
                  </optgroup>
                  <!-- 阿里云通义千问 -->
                  <optgroup label="阿里云通义千问">
                    <option value="qwen-max">通义千问 Max</option>
                    <option value="qwen-plus">通义千问 Plus</option>
                    <option value="qwen-turbo">通义千问 Turbo</option>
                    <option value="qwen-long">通义千问 Long</option>
                  </optgroup>
                  <!-- 百度文心一言 -->
                  <optgroup label="百度文心一言">
                    <option value="ernie-4.0-8k">文心一言 4.0</option>
                    <option value="ernie-3.5-8k">文心一言 3.5</option>
                    <option value="ernie-turbo-8k">文心一言 Turbo</option>
                  </optgroup>
                  <!-- 智谱AI -->
                  <optgroup label="智谱AI">
                    <option value="glm-4-plus">GLM-4 Plus</option>
                    <option value="glm-4-0520">GLM-4</option>
                    <option value="glm-4-air">GLM-4 Air</option>
                    <option value="glm-4-flash">GLM-4 Flash</option>
                  </optgroup>
                  <!-- 月之暗面 Kimi -->
                  <optgroup label="月之暗面">
                    <option value="moonshot-v1-8k">Kimi 8K</option>
                    <option value="moonshot-v1-32k">Kimi 32K</option>
                    <option value="moonshot-v1-128k">Kimi 128K</option>
                  </optgroup>
                  <!-- 零一万物 -->
                  <optgroup label="零一万物">
                    <option value="yi-large">Yi Large</option>
                    <option value="yi-medium">Yi Medium</option>
                    <option value="yi-spark">Yi Spark</option>
                  </optgroup>
                  <!-- 其他模型 -->
                  <optgroup label="其他">
                    <option value="custom">自定义模型</option>
                  </optgroup>
                </select>
                <!-- 自定义模型输入框 -->
                <input
                  v-if="formData.model === 'custom'"
                  v-model="customModel"
                  type="text"
                  placeholder="请输入自定义模型名称"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent mt-2"
                  @input="formData.model = customModel"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">API Key</label>
                <div class="relative">
                  <input
                    v-model="formData.apiKey"
                    :type="showApiKey ? 'text' : 'password'"
                    required
                    class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    placeholder="输入API密钥"
                  />
                  <button
                    type="button"
                    @click="showApiKey = !showApiKey"
                    class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                  >
                    <svg v-if="showApiKey" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                    <svg v-else class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                    </svg>
                  </button>
                </div>
              </div>
              <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-2">Base URL</label>
                <input
                  v-model="formData.baseUrl"
                  type="url"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="例如：https://api.openai.com/v1"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Temperature</label>
                <input
                  v-model.number="formData.temperature"
                  type="number"
                  min="0"
                  max="2"
                  step="0.1"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Max Tokens</label>
                <input
                  v-model.number="formData.maxTokens"
                  type="number"
                  min="1"
                  max="8192"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
            </div>
            <div class="flex items-center space-x-6">
              <div class="flex items-center">
                <input
                  v-model="formData.isActive"
                  type="checkbox"
                  id="isActive"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
                <label for="isActive" class="ml-2 block text-sm text-gray-900">
                  启用此配置
                </label>
              </div>
              <div class="flex items-center">
                <input
                  v-model="formData.isDefault"
                  type="checkbox"
                  id="isDefault"
                  class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
                <label for="isDefault" class="ml-2 block text-sm text-gray-900">
                  设为默认配置
                </label>
              </div>
            </div>
            <div class="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                取消
              </button>
              <button
                type="submit"
                :disabled="isSaving"
                class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
              >
                {{ isSaving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message.show" :class="messageClass" class="fixed top-4 right-4 p-4 rounded-md shadow-lg z-50">
      <div class="flex">
        <div class="flex-shrink-0">
          <svg v-if="message.type === 'success'" class="h-5 w-5 text-green-400" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
          </svg>
          <svg v-else class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
          </svg>
        </div>
        <div class="ml-3">
          <p class="text-sm font-medium">{{ message.text }}</p>
        </div>
        <div class="ml-auto pl-3">
          <button @click="hideMessage" class="inline-flex text-gray-400 hover:text-gray-600">
            <svg class="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
              <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useModelConfigStore, type ModelConfig } from '@/stores/modelConfig'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const modelConfigStore = useModelConfigStore()
const authStore = useAuthStore()

// 响应式数据
const showAddModal = ref(false)
const showEditModal = ref(false)
const isSaving = ref(false)
const testingConfigId = ref<string | null>(null)
const editingConfig = ref<ModelConfig | null>(null)
const customModel = ref('')
const showApiKey = ref(false)

// 表单数据
const formData = ref<Partial<ModelConfig>>({
  name: '',
  provider: '',
  model: '',
  apiKey: '',
  baseUrl: '',
  temperature: 0.7,
  maxTokens: 1000,
  isActive: true,
  isDefault: false
})

// 消息提示
const message = ref({
  show: false,
  type: 'success' as 'success' | 'error',
  text: ''
})

const messageClass = computed(() => {
  return message.value.type === 'success'
    ? 'bg-green-50 border border-green-200 text-green-800'
    : 'bg-red-50 border border-red-200 text-red-800'
})

// 方法
const showMessage = (text: string, type: 'success' | 'error' = 'success') => {
  message.value = { show: true, type, text }
  setTimeout(() => {
    message.value.show = false
  }, 3000)
}

const hideMessage = () => {
  message.value.show = false
}

const getProviderIconClass = (provider: string) => {
  const classes = {
    openai: 'bg-green-100 text-green-600',
    claude: 'bg-purple-100 text-purple-600',
    qwen: 'bg-blue-100 text-blue-600',
    deepseek: 'bg-orange-100 text-orange-600'
  }
  return classes[provider as keyof typeof classes] || 'bg-gray-100 text-gray-600'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const resetFormData = () => {
  formData.value = {
    name: '',
    provider: '',
    model: '',
    apiKey: '',
    baseUrl: '',
    temperature: 0.7,
    maxTokens: 1000,
    isActive: true,
    isDefault: false
  }
  customModel.value = ''
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingConfig.value = null
  resetFormData()
}

const editConfig = (config: ModelConfig) => {
  editingConfig.value = config
  // 将后端数据结构转换为表单数据格式
  formData.value = {
    ...config,
    baseUrl: config.apiUrl || config.baseUrl || '',
    temperature: Number(config.parameters?.temperature) || config.temperature || 0.7,
    maxTokens: config.parameters?.maxTokens || config.maxTokens || 1000,
    isActive: config.isActive !== undefined ? config.isActive : true,
    isDefault: config.isDefault || false
  }
  
  // 检查是否为自定义模型
  const predefinedModels = [
    'gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo',
    'claude-3-opus', 'claude-3-sonnet', 'claude-3-haiku',
    'qwen-turbo', 'qwen-plus', 'qwen-max',
    'deepseek-chat', 'deepseek-reasoner', 'deepseek-coder',
    'glm-4', 'glm-3-turbo',
    'yi-34b-chat', 'yi-6b-chat',
    'baichuan2-13b-chat', 'baichuan2-7b-chat',
    'chatglm3-6b', 'chatglm2-6b'
  ]
  
  if (!predefinedModels.includes(config.model)) {
    formData.value.model = 'custom'
    customModel.value = config.model
  } else {
    customModel.value = ''
  }
  
  showEditModal.value = true
}

const saveConfig = async () => {
  try {
    // 检查用户是否已登录
    if (!authStore.isAuthenticated) {
      showMessage('请先登录后再访问模型配置', 'error')
      router.push('/login')
      return
    }
    
    isSaving.value = true
    
    const configData: ModelConfig = {
      ...formData.value as ModelConfig
    }
    
    // 处理自定义模型
    if (formData.value.model === 'custom' && customModel.value.trim()) {
      configData.model = customModel.value.trim()
    }
    
    if (editingConfig.value) {
      configData.id = editingConfig.value.id
    }
    
    const result = await modelConfigStore.saveConfig(configData)
    
    if (result.success) {
      showMessage(result.message || '保存成功')
      closeModal()
      // 刷新页面以显示最新的配置
      setTimeout(() => {
        window.location.reload()
      }, 1000) // 延迟1秒刷新，让用户看到成功消息
    } else {
      showMessage(result.message || '保存失败', 'error')
    }
  } catch (error) {
    console.error('保存配置失败:', error)
    showMessage('保存配置时发生错误', 'error')
  } finally {
    isSaving.value = false
  }
}

const deleteConfig = async (config: ModelConfig) => {
  if (!config.id) return
  
  if (confirm(`确定要删除配置 "${config.name}" 吗？`)) {
    try {
      const result = await modelConfigStore.deleteConfig(config.id)
      if (result.success) {
        showMessage(result.message || '删除成功')
      } else {
        showMessage(result.message || '删除失败', 'error')
      }
    } catch (error) {
      console.error('删除配置失败:', error)
      showMessage('删除配置时发生错误', 'error')
    }
  }
}

const testConfig = async (config: ModelConfig) => {
  try {
    testingConfigId.value = config.id || null
    const result = await modelConfigStore.testConnection(config)
    
    if (result.success) {
      showMessage('连接测试成功')
    } else {
      showMessage(result.message || '连接测试失败', 'error')
    }
  } catch (error) {
    console.error('测试连接失败:', error)
    showMessage('测试连接时发生错误', 'error')
  } finally {
    testingConfigId.value = null
  }
}

// 生命周期
onMounted(async () => {
  // 检查用户是否已登录
  if (!authStore.isAuthenticated) {
    showMessage('请先登录后再访问模型配置', 'error')
    router.push('/login')
    return
  }
  
  await modelConfigStore.loadConfigs()
})
</script>